﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Text;
using System.Reflection;
using System.Data.Linq.Mapping;
using BulletOnRails4NET.Models;
using Suteki.Common.Repositories;

namespace BulletOnRails4NET.Controllers
{
    public class AssociationQueryInfo
    {
        public IQueryable<IDLabelPair> AssociationsListQuery { get; set; }
        public string FkColumnName { get; set; }
        public int CurrIdSelected { get; set; }
        public AssociationQueryInfo(string fk_column_name, IQueryable<IDLabelPair> associations_list_query)
        {
            AssociationsListQuery = associations_list_query;
            FkColumnName = fk_column_name;
        }
    }

    public class AssociationFormHelper
    {

        public static Dictionary<string, string> CreateAssociationHTMLFields(List<AssociationQueryInfo> associations_info)
        {
            Dictionary<string, string> fields = new Dictionary<string, string>();
            
            
            foreach (AssociationQueryInfo association_info in associations_info)
            {
                StringBuilder html_select_builder = new StringBuilder("<p><label for=\"");

                html_select_builder.Append(association_info.FkColumnName);
                html_select_builder.Append("\">");
                html_select_builder.Append(association_info.FkColumnName.HumanizeString());
                html_select_builder.Append("</label>");
                html_select_builder.Append(
                    "<select id=\"" + association_info.FkColumnName +
                    "\" name=\"" + association_info.FkColumnName + "\">");

                var rows = (association_info.AssociationsListQuery.Select(c =>

            new
            {

                id = c.ID,

                label = c.Label

            }
        )).ToList();

                foreach (var row in rows)
                {
                    html_select_builder.AppendLine("<option value=\"");
                    html_select_builder.Append(row.id);
                    if (row.id == association_info.CurrIdSelected)
                        html_select_builder.Append("\" selected=\"selected\" >"); 
                    else
                        html_select_builder.Append("\" >"); 
                    html_select_builder.Append(row.label);
                    html_select_builder.Append("</option>");
                }
                html_select_builder.Append("</select>");
                html_select_builder.Append("</p>");
                fields.Add(association_info.FkColumnName, html_select_builder.ToString());
            }
            return fields;
        }

        

    }
}
